package contacts.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import contacts.dao.IRoomDao;
import contacts.db.DbConnection;
import contacts.po.Room;
import contacts.po.Student;

public class RoomDaoImpl implements IRoomDao{

	@Override
	public void save(Room room) {
		Connection conn=DbConnection.getConnection();
		PreparedStatement ps = null;
		try {
			String sql = "insert into room values(?,?)";
			ps  = conn.prepareStatement(sql);	
			ps.setInt(1, room.getRoomNo());
			ps.setString(2, room.getRoomName());
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DbConnection.close(ps, null);
		}	
	}
	@Override
	public void update(Room room) {
		Connection conn=DbConnection.getConnection();
		PreparedStatement ps = null;
		try {
			String sql = "update room set room_name=?where room_no=?";
			ps  = conn.prepareStatement(sql);	
			ps.setString(1, room.getRoomName());
			ps.setInt(2, room.getRoomNo());
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DbConnection.close(ps, null);
		}	
		
	}

	@Override
	public Room get(int rNo) {
		Connection conn=DbConnection.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		List<Room> roomList=new ArrayList<Room>();
		
		try {
			String sql="select room_no,room_name from room where room_no=?";
			ps=conn.prepareStatement(sql);
			ps.setInt(1, rNo);
			ps.execute();
			rs=ps.executeQuery();
			while(rs.next()) {
				int roomNo=rs.getInt(1);
				String roomName=rs.getString(2);
				Room room=new Room(roomNo,roomName);
				roomList.add(room);
			}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				DbConnection.close(ps, null);
			}
			return roomList.get(0);
	}

	@Override
	public void delete(int rNo) {
		Connection conn = DbConnection.getConnection();
		PreparedStatement ps = null;
		
		try {
			String sql = "delete from room where room_no=?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, rNo);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbConnection.close(ps, null);
		}
		
	}
	@Override
	public List<Room> findAll() {
		Connection conn=DbConnection.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		List<Room> roomList=new ArrayList<Room>();
		try {
			String sql="select room_no,room_name from room";
			ps=conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()) {
				int roomNo=rs.getInt(1);
				String roomName=rs.getString(2);
				Room room=new Room(roomNo,roomName);
				roomList.add(room);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbConnection.close(ps, null);
		}
		return roomList;
	}
}


